package com.cskaoyan.mall.filter;

import com.cskaoyan.mall.util.Constant;
import com.cskaoyan.mall.util.Result;
import com.google.gson.Gson;

import javax.servlet.*;
import javax.servlet.annotation.WebFilter;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;
import java.io.IOException;

/**
 * @author: jyf2000jyf
 */
@WebFilter("/api/mall/*")
public class MallFilter implements Filter {
    public void destroy() {
    }

    public void doFilter(ServletRequest req, ServletResponse resp, FilterChain chain) throws ServletException, IOException {
        HttpServletRequest request = (HttpServletRequest) req;
        HttpServletResponse response = (HttpServletResponse) resp;
        req.setCharacterEncoding("utf-8");
        resp.setContentType("text/html;charset=utf-8");
        //跨域时服务器的授权
        response.setHeader("Access-Control-Allow-Origin", Constant.origin);
        response.setHeader("Access-Control-Allow-Methods", "POST,GET,OPTIONS,PUT,DELETE");
        response.setHeader("Access-Control-Allow-Headers", "x-requested-with,Authorization,Content-Type");
        response.setHeader("Access-Control-Allow-Credentials", "true");
        String requestURI = request.getRequestURI();
        String method = request.getMethod();
        if (requestURI.contains(request.getContextPath() + "/api/mall/index")) {
            chain.doFilter(req, resp);
            return;
        }
        if (!"OPTIONS".equals(method)) {
            if (!(request.getContextPath() + "/api/mall/user/login").equals(requestURI) && !(request.getContextPath() + "/api/mall/user/signup").equals(requestURI)
                    && !(request.getContextPath() + "/api/mall/goods/getGoodsByType").equals(requestURI)) {
                HttpSession session = request.getSession();
                Object userEmail = session.getAttribute("userEmail");
                if (userEmail == null) {
                    Result result = new Result(10000, "当前页面仅允许登录后访问!!!", null);
                    response.getWriter().println(new Gson().toJson(result));
                    return;
                }
            }
        }
        chain.doFilter(req, resp);
    }

    public void init(FilterConfig config) throws ServletException {

    }

}
